﻿using Newtonsoft.Json;
using SchoolTools.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SchoolTools
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private FloatingBallWindow floatingWindow;
        private enum DockDirection { Left, Right }
        private readonly string[] _encouragements = {
    // 原5条
    "太棒了！", "继续努力！", "完美！", "不可思议！", "哇！",
    
    // 新增20条（按激励强度递增）
    // 基础激励（适合0-50分）
    "再接再厉！",
    "进步明显！",
    "渐入佳境！",
    
    // 中级激励（50-150分）
    "势如破竹！",
    "火力全开！",
    "乘胜追击！",
    "突飞猛进！",
    "666！",      // 网络用语增强亲切感
    "秀儿是你吗？", // 趣味网络梗
    
    // 高级激励（150-300分）
    "一骑绝尘！",
    "无人能挡！",
    "王者风范！",
    "开挂了吧！",  // 趣味性表达
    "这合理吗？",  // 疑问句式增强互动
    
    // 顶级激励（300+分）
    "登峰造极！",
    "天神下凡！",
    "破纪录啦！",
    "这是要逆天啊！", // 夸张语气
    
    //// 特殊场景（连击/快速得分）
    //"连击x3！",
    //"手速惊人！",
    //"根本停不下来！",
    
    // 团队协作
    //"最佳团队！",
    //"配合无间！"
};
        private bool _isFirstCollapse = true;
        private Point _lastFloatPosition;
        private const string DataFile = "scores.json";
        private bool _isDragging;
        // 添加字段保存位置
        private Point _floatBallPosition = new Point(20, 800);

        public ObservableCollection<StudentGroup> Groups { get; } = new ObservableCollection<StudentGroup>();

        public MainWindow()
        {
            InitializeComponent();
            LoadGroups();
            UpdateGroupLayout();
            DataContext = this;
            Groups.CollectionChanged += Groups_CollectionChanged;
        }
        private void Groups_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            UpdateGroupLayout();
        }
        private void UpdateGroupLayout()
        {
            // 等待布局完成后再获取 UniformGrid
            Dispatcher.BeginInvoke(new Action(() =>
            {
                var panel = GetItemsHostPanel(GroupsContainer) as UniformGrid;
                if (panel == null) return;

                int count = Groups.Count;

                if (count <= 2)
                    panel.Columns = 2;
                else if (count <= 4)
                    panel.Columns = count;
                else
                    panel.Columns = 4;
            }), System.Windows.Threading.DispatcherPriority.Loaded);
        }
        private Panel GetItemsHostPanel(ItemsControl itemsControl)
        {
            return FindVisualChild<Panel>(itemsControl);
        }

        private void LoadGroups()
        {
            if (File.Exists(DataFile))
            {
                var json = File.ReadAllText(DataFile);
                var groups = JsonConvert.DeserializeObject<ObservableCollection<StudentGroup>>(json);
                Groups.Clear();
                foreach (var group in groups)
                {
                    Groups.Add(group);
                }
            }
            else
            {
                InitializeDefaultGroups();
            }
        }

        private void InitializeDefaultGroups()
        {
            for (int i = 1; i <= 6; i++)
            {
                Groups.Add(new StudentGroup($"第{i}组"));
            }
        }

        private void SaveGroups()
        {
            var json = JsonConvert.SerializeObject(Groups);
            File.WriteAllText(DataFile, json);
        }
        /// <summary>
        /// 显示鼓励语
        /// </summary>
        private void ShowEncouragement()
        {
            var random = new Random();
            EncouragementText.Text = _encouragements[random.Next(_encouragements.Length)];

            var animation = new DoubleAnimation
            {
                From = 0,
                To = 1,
                Duration = TimeSpan.FromSeconds(0.5),
                AutoReverse = true
            };
            EncouragementText.BeginAnimation(OpacityProperty, animation);
        }

        #region 窗口行为
        
       

        private void AddScore_Click(object sender, RoutedEventArgs e)
        {
            if (((FrameworkElement)sender).Tag is StudentGroup group)
            {
                group.Score += 10;
                ShowEncouragement();
                AnimateScoreChange(group);
            }
        }

        private void SubtractScore_Click(object sender, RoutedEventArgs e)
        {
            if (((FrameworkElement)sender).Tag is StudentGroup group)
            {
                group.Score = Math.Max(0, group.Score - 10);
                //ShowEncouragement();
                AnimateScoreChange(group);
            }
        }
        private void AddGroup_Click(object sender, RoutedEventArgs e)
        {
            int nextNumber = Groups.Count + 1;
            string name = $"第{nextNumber}组";

            // 确保名称唯一
            int suffix = 1;
            while (Groups.Any(g => g.GroupName == name))
            {
                name = $"第{nextNumber + suffix++}组";
            }

            Groups.Add(new StudentGroup(name));
        }
       
        private void DeleteGroup_Click(object sender, RoutedEventArgs e)
        {
            if (((FrameworkElement)sender).Tag is StudentGroup group)
            {
                var result = MessageBox.Show($"确定要删除 {group.GroupName} 吗？", "删除确认", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    Groups.Remove(group);
                }
            }
        }

        #endregion

        #region 命令处理
        private void AnimateScoreChange(StudentGroup group)
        {
            var container = GroupsContainer.ItemContainerGenerator.ContainerFromItem(group);
            var textBlock = FindVisualChild<TextBlock>(container);

            var animation = new DoubleAnimation
            {
                From = 1,
                To = 1.2,
                Duration = TimeSpan.FromSeconds(0.2),
                AutoReverse = true
            };

            var transform = new ScaleTransform();
            textBlock.RenderTransform = transform;
            transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
            transform.BeginAnimation(ScaleTransform.ScaleYProperty, animation);
        }
        #endregion

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SaveGroups();
        }
       
        private void ResetAll_Click(object sender, RoutedEventArgs e)
        {
            // 添加确认对话框
            var result = MessageBox.Show("确定要重置所有小组的分数吗？",
                                       "确认重置",
                                       MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                foreach (var group in Groups)
                {
                    group.Score = 0;
                }

                // 播放重置动画
                AnimateResetAll();
            }
        }

        private void AnimateResetAll()
        {
            var animation = new DoubleAnimation
            {
                From = 1,
                To = 0.5,
                Duration = TimeSpan.FromSeconds(0.5),
                AutoReverse = true
            };

            foreach (var item in GroupsContainer.Items)
            {
                var container = GroupsContainer.ItemContainerGenerator.ContainerFromItem(item);
                var border = FindVisualChild<Border>(container);
                border?.BeginAnimation(OpacityProperty, animation);
            }
        }
        
        // 泛型方法实现
        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            if (obj == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is T result)
                    return result;

                var childResult = FindVisualChild<T>(child);
                if (childResult != null)
                    return childResult;
            }
            return null;
        }

        // 带条件过滤的重载
        private static T FindVisualChild<T>(DependencyObject obj, Func<T, bool> predicate)
            where T : DependencyObject
        {
            if (obj == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is T result && predicate(result))
                    return result;

                var childResult = FindVisualChild(child, predicate);
                if (childResult != null)
                    return childResult;
            }
            return null;
        }
        // 切换至悬浮球模式（隐藏主窗口，显示悬浮球）
        private void EnterFloatingMode_Click(object sender, RoutedEventArgs e)
        {
            // 隐藏主窗口
            this.Hide();
            // 创建并显示悬浮球窗口
            floatingWindow = new FloatingBallWindow();
            // 当悬浮球双击时恢复主界面
            floatingWindow.MouseDoubleClick += (s, ev) =>
            {
                floatingWindow.Close();
                this.Show();
            };

            floatingWindow.Show();
        }

       
        // 添加通用触摸处理
        private void Button_TouchDown(object sender, TouchEventArgs e)
        {
            if (sender is Button btn && btn.Command != null)
            {
                btn.Command.Execute(btn.CommandParameter);
            }
            e.Handled = true;
        }
    }
}
